package com.jk.util;

import org.json.JSONObject;
import org.smart4j.framework.util.StringUtil;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class RequestParamUtil {


	/**
	 * 解析请求消息体中的内容
	 * @param request
	 * @return 消息体内容String
	 * @throws UnsupportedEncodingException 
	 */
	public static String getRequestContents(HttpServletRequest request){
		try {
			request.setCharacterEncoding("utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		BufferedInputStream bufferedInputStream = null;
		StringBuffer returnStr = new StringBuffer();
		try {
			byte[] bytes = new byte[1024];
				
			bufferedInputStream = new BufferedInputStream(request.getInputStream());
			int iRead;
			while ((iRead = bufferedInputStream.read(bytes)) != -1) {
				returnStr.append(new String(bytes, 0, iRead, "UTF-8"));
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (bufferedInputStream != null) {
					bufferedInputStream.close();
				}
				
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return returnStr.toString();
	}




	/**
	 * 获取请求参数序列号为集合
	 * <pre>
	 * Author: shujiang.yang
	 * @param
	 * @return
	 * Modifications:
	 * Modifier shujiang.yang; 2014-3-5; Create new Method
	 * </pre>
	 */
	public static final Map<String, String> getRequestParams(HttpServletRequest request) {
		String jsonStr = getRequestContents(request);

		Map<String, String> result = new HashMap<String, String>();
		try {
			if (StringUtil.isEmpty(jsonStr)) {
				return result;
			}

			JSONObject jsonObject = new JSONObject(jsonStr);
			Iterator iterator = jsonObject.keys();
			String key = "";
			String value = "";
			while (iterator.hasNext()) {
				key = (String) iterator.next();
				value = jsonObject.getString(key);
				if (StringUtil.isEmpty(value)) {
					continue;
				}
				result.put(key, value);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}